import React, { useState, useEffect } from 'react';
import {
  View,
  TouchableOpacity,
  Text,
  StyleSheet,
  Animated,
  PanResponder,
  Dimensions,
  Image
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { 
  startAutoScroll, 
  pauseAutoScroll, 
  resumeAutoScroll, 
  stopAutoScroll,
  selectIsAutoScrolling,
  selectIsPaused,
  selectCurrentPlatform
} from '../../store/slices/autoScrollSlice';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

const FloatingButton = () => {
  const dispatch = useDispatch();
  const isAutoScrolling = useSelector(selectIsAutoScrolling);
  const isPaused = useSelector(selectIsPaused);
  const currentPlatform = useSelector(selectCurrentPlatform);
  
  const [position] = useState(new Animated.ValueXY({ x: screenWidth - 80, y: 100 }));
  const [opacity] = useState(new Animated.Value(0.8));
  const [isDragging, setIsDragging] = useState(false);

  // 创建拖拽响应器
  const panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onMoveShouldSetPanResponder: () => true,
    
    onPanResponderGrant: () => {
      setIsDragging(true);
      position.setOffset({
        x: position.x._value,
        y: position.y._value
      });
      position.setValue({ x: 0, y: 0 });
      
      // 拖拽时增加透明度
      Animated.timing(opacity, {
        toValue: 1,
        duration: 200,
        useNativeDriver: false
      }).start();
    },
    
    onPanResponderMove: Animated.event(
      [
        null,
        { dx: position.x, dy: position.y }
      ],
      { useNativeDriver: false }
    ),
    
    onPanResponderRelease: (evt, gestureState) => {
      setIsDragging(false);
      position.flattenOffset();
      
      // 恢复原始透明度
      Animated.timing(opacity, {
        toValue: 0.8,
        duration: 200,
        useNativeDriver: false
      }).start();
      
      // 边界检测和自动吸附
      const finalX = position.x._value;
      const finalY = position.y._value;
      const buttonSize = 60;
      const margin = 10;
      
      let targetX = finalX;
      let targetY = finalY;
      
      // 水平边界
      if (finalX < margin) {
        targetX = margin;
      } else if (finalX > screenWidth - buttonSize - margin) {
        targetX = screenWidth - buttonSize - margin;
      }
      
      // 垂直边界
      if (finalY < margin) {
        targetY = margin;
      } else if (finalY > screenHeight - buttonSize - margin - 100) {
        targetY = screenHeight - buttonSize - margin - 100;
      }
      
      // 自动吸附到边缘
      const centerX = targetX + buttonSize / 2;
      if (centerX < screenWidth / 2) {
        targetX = margin;
      } else {
        targetX = screenWidth - buttonSize - margin;
      }
      
      Animated.spring(position, {
        toValue: { x: targetX, y: targetY },
        friction: 8,
        tension: 40,
        useNativeDriver: false
      }).start();
    }
  });

  // 获取按钮图标
  const getButtonIcon = () => {
    if (isAutoScrolling) {
      if (isPaused) {
        return '▶️'; // 播放图标
      } else {
        return '⏸️'; // 暂停图标
      }
    } else {
      return '▶️'; // 开始图标
    }
  };

  // 获取按钮背景色
  const getButtonColor = () => {
    if (isAutoScrolling) {
      if (isPaused) {
        return '#FFA500'; // 橙色 - 暂停状态
      } else {
        return '#FF4444'; // 红色 - 运行状态
      }
    } else {
      return '#4CAF50'; // 绿色 - 停止状态
    }
  };

  // 处理按钮点击
  const handleButtonPress = () => {
    if (isDragging) return;
    
    if (isAutoScrolling) {
      if (isPaused) {
        dispatch(resumeAutoScroll());
      } else {
        dispatch(pauseAutoScroll());
      }
    } else {
      dispatch(startAutoScroll());
    }
  };

  // 处理长按（停止自动滑动）
  const handleLongPress = () => {
    if (isAutoScrolling) {
      dispatch(stopAutoScroll());
    }
  };

  // 获取平台图标
  const getPlatformIcon = () => {
    const platformIcons = {
      douyin: '🎵',
      kuaishou: '📱',
      xigua: '🍉',
      bilibili: '📺',
      weishi: '⏱️',
      local: '📁'
    };
    
    return platformIcons[currentPlatform] || '📱';
  };

  return (
    <Animated.View
      style={[
        styles.container,
        {
          transform: [
            { translateX: position.x },
            { translateY: position.y }
          ],
          opacity: opacity
        }
      ]}
      {...panResponder.panHandlers}
    >
      <TouchableOpacity
        style={[styles.button, { backgroundColor: getButtonColor() }]}
        onPress={handleButtonPress}
        onLongPress={handleLongPress}
        delayLongPress={1000}
        activeOpacity={0.8}
      >
        <Text style={styles.buttonText}>{getButtonIcon()}</Text>
      </TouchableOpacity>
      
      {/* 平台指示器 */}
      <View style={styles.platformIndicator}>
        <Text style={styles.platformIcon}>{getPlatformIcon()}</Text>
      </View>
      
      {/* 状态指示器 */}
      {isAutoScrolling && (
        <View style={[
          styles.statusIndicator,
          isPaused ? styles.pausedIndicator : styles.runningIndicator
        ]}>
          <Text style={styles.statusText}>
            {isPaused ? '⏸️' : '▶️'}
          </Text>
        </View>
      )}
      
      {/* 统计信息 */}
      {isAutoScrolling && (
        <View style={styles.statsContainer}>
          <Text style={styles.statsText}>
            {isPaused ? '已暂停' : '运行中'}
          </Text>
        </View>
      )}
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    zIndex: 999,
    elevation: 8,
  },
  button: {
    width: 60,
    height: 60,
    borderRadius: 30,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  buttonText: {
    fontSize: 24,
    color: '#FFFFFF',
    fontWeight: 'bold',
  },
  platformIndicator: {
    position: 'absolute',
    top: -5,
    right: -5,
    backgroundColor: '#FFFFFF',
    borderRadius: 12,
    width: 24,
    height: 24,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,
    elevation: 2,
  },
  platformIcon: {
    fontSize: 14,
  },
  statusIndicator: {
    position: 'absolute',
    bottom: -5,
    left: -5,
    borderRadius: 10,
    width: 20,
    height: 20,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,
    elevation: 2,
  },
  pausedIndicator: {
    backgroundColor: '#FFA500',
  },
  runningIndicator: {
    backgroundColor: '#4CAF50',
  },
  statusText: {
    fontSize: 12,
    color: '#FFFFFF',
  },
  statsContainer: {
    position: 'absolute',
    top: 70,
    left: -20,
    right: -20,
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
    borderRadius: 8,
    padding: 8,
    minWidth: 80,
    alignItems: 'center',
  },
  statsText: {
    color: '#FFFFFF',
    fontSize: 12,
    fontWeight: 'bold',
  },
});

export default FloatingButton;